<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import v_guide_api from '@/api/visitor/v_guide_api.js'
import booking_api from '@/api/visitor/booking_api.js'
import {getJwtPayload} from "@/util/auth.js";
import transaction_api from "@/api/visitor/transaction_api.js";
import visitor_api from "@/api/visitor/visitor_api.js"
import vRateApi from '@/api/visitor/v_rate_api.js'
// 引入AI聊天插件
import '../../ai-chat-plugin.js'

const searchObj = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  username: '',
  gender: '',
  position: '',
})

const bookings = ref([])
// 添加预约记录分页数据
const bookingPage = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0
})

const guides = ref({
  data: [],
  totalCount: 0
})

// 预约相关数据
const bookingDialogVisible = ref(false)
const selectedGuide = ref({})
const bookingForm = ref({
  startTime: '',
  endTime: '',
  days: 0,
  visitorPayment: 0
})

// 评分相关数据
const ratingDialogVisible = ref(false)
const ratingForm = ref({
  guideId: null,
  rates: 5
})
const currentBooking = ref({})

// 当前登录的游客ID（实际应该从登录信息中获取）
const currentVisitorId = ref(null)

// 处理OSS图片URL
const getOssImageUrl = (imageUrl) => {
  if (!imageUrl || imageUrl.trim() === '') {
    return 'https://via.placeholder.com/40x40?text=No+Image';
  }
  if (imageUrl.startsWith('http')) {
    return imageUrl;
  }
  const bucketName = 'java-dz';
  const endpoint = 'oss-cn-beijing.aliyuncs.com';
  return `https://${bucketName}.${endpoint}/${imageUrl}`;
}

// 计算属性：过滤可用地陪（移除对isAvailable的依赖，因为后端已删除该字段）
const availableGuides = computed(() => {
  return guides.value.data;
})

onMounted(async () => {
  // 从token中获取当前用户ID
  const payload = getJwtPayload();
  if (!payload || (payload.ID == null && payload.id == null)) {
    ElMessage.error('未从 token 中读取到用户 ID');
    return;
  }
  currentVisitorId.value = Number(payload.ID ?? payload.id);
  // 加载游客信息
  await loadVisitorProfile();

  await loadGuides()
  await loadBookings()
})

// 加载地陪列表
const loadGuides = async () => {
  try {
    const params = {
      ...searchObj.value
    };

    const result = await v_guide_api.page(params)

    if (result && result.data) {
      // 处理可能的不同数据结构
      let guideData = [];
      if (Array.isArray(result.data)) {
        guideData = result.data;
        guides.value.totalCount = result.totalCount || guideData.length;
      } else if (result.data.data && Array.isArray(result.data.data)) {
        guideData = result.data.data;
        guides.value.totalCount = result.data.totalCount || result.totalCount || guideData.length;
      } else {
        guideData = [];
        guides.value.totalCount = 0;
      }

      guides.value.data = guideData;

      // 加载每个地陪的评分
      await loadRatesForGuides();
    }
  } catch (error) {
    console.error('加载地陪列表失败:', error);
    ElMessage.error('加载地陪列表失败: ' + error.message)
  }
}

// 为所有地陪加载评分
const loadRatesForGuides = async () => {
  if (!guides.value.data || guides.value.data.length === 0) return;

  try {
    const promises = guides.value.data.map(async (guide) => {
      try {
        const res = await vRateApi.getRate({ guideId: guide.id });
        guide.rate = res ? parseFloat(res.toFixed(1)) : 0;
      } catch (error) {
        console.error(`加载地陪${guide.id}评分失败:`, error);
        guide.rate = 0;
      }
    });

    await Promise.all(promises);
  } catch (error) {
    console.error('批量加载评分失败:', error);
  }
}

// 加载预约记录（分页）
const loadBookings = async () => {
  if (!currentVisitorId.value) {
    ElMessage.warning('未获取到用户信息');
    return;
  }

  try {
    const result = await booking_api.page({
      visitorId: currentVisitorId.value,
      currentPage: bookingPage.value.currentPage,
      pageSize: bookingPage.value.pageSize
    });

    if (result && result.data) {
      bookingPage.value.totalCount = result.totalCount || 0;

      let bookingData = [];
      if (Array.isArray(result.data)) {
        bookingData = result.data;
      } else if (result.data.data && Array.isArray(result.data.data)) {
        bookingData = result.data.data;
      } else {
        bookingData = [];
      }

      // 为每个预约记录检查是否已评分
      const updatedBookingData = await Promise.all(bookingData.map(async (item) => {
        // 默认设置为未评分
        let isRated = 0;

        // 如果已支付，检查是否已评分
        if (item.isPaid) {
          try {
            // 通过查询评分来判断是否已评分
            const rateResult = await vRateApi.checkRate({
              visitorId: currentVisitorId.value,
              guideId: item.guideId
            });

            isRated = rateResult ? 1 : 0;
          } catch (error) {
            console.error(`检查预约${item.id}评分状态失败:`, error);
          }
        }

        return {
          id: item.id,
          guideId: item.guideId,
          guideName: item.guideName || '未知地陪',
          startDate: formatDate(item.startTime),
          endDate: formatDate(item.endTime),
          days: item.days,
          amount: (item.visitorPayment ? item.visitorPayment : 0) + '元',
          status: item.isDeleted === 1 ? '已取消' : '已预约',
          isDeleted: item.isDeleted,
          isPaid: item.isPaid || 0,
          // 添加原始数据用于取消预约
          rawData: item,
          // 使用检查结果或后端提供的状态
          isRated: isRated
        };
      }));

      bookings.value = updatedBookingData;
    }
  } catch (error) {
    console.error('加载预约记录失败:', error);
    ElMessage.error('加载预约记录失败: ' + error.message);
  }
}

// 查询功能
const handleSearch = async () => {
  searchObj.value.currentPage = 1
  await loadGuides()
}

// 重置查询条件
const handleReset = async () => {
  searchObj.value = {
    currentPage: 1,
    pageSize: 10,
    totalCount: 0,
    username: '',
    gender: '',
    position: ''
  }
  await loadGuides()
}

// 地陪分页功能
const handleSizeChange = async (val) => {
  searchObj.value.pageSize = val
  searchObj.value.currentPage = 1
  await loadGuides()
}

const handleCurrentChange = async (val) => {
  searchObj.value.currentPage = val
  await loadGuides()
}

// 预约记录分页功能
const handleBookingSizeChange = async (val) => {
  bookingPage.value.pageSize = val
  bookingPage.value.currentPage = 1
  await loadBookings()
}

const handleBookingCurrentChange = async (val) => {
  bookingPage.value.currentPage = val
  await loadBookings()
}

// 打开预约对话框
const openBookingDialog = (guide) => {
  selectedGuide.value = guide
  bookingForm.value = {
    startTime: '',
    endTime: '',
    days: 0,
    visitorPayment: 0
  }
  bookingDialogVisible.value = true
}

// 修改禁用开始日期的逻辑：只能选择3天后的日期
const disabledStartDate = (time) => {
  // 获取当前时间 + 3天
  const minDate = new Date();
  minDate.setDate(minDate.getDate() + 3);
  // 设置为当天凌晨，避免时间部分影响比较
  minDate.setHours(0, 0, 0, 0);

  // 禁用3天内的日期（包括今天）
  return time.getTime() < minDate.getTime();
}

// 禁用结束日期（可以选开始日期及以后的日期）
const disabledEndDate = (time) => {
  if (!bookingForm.value.startTime) {
    // 如果没有选择开始时间，结束时间也至少要是3天后
    const minDate = new Date();
    minDate.setDate(minDate.getDate() + 3);
    minDate.setHours(0, 0, 0, 0);
    return time.getTime() < minDate.getTime();
  }
  // 允许选择开始日期及之后的日期（包括当天）
  return time.getTime() < new Date(bookingForm.value.startTime).getTime();
}

// 监听开始和结束时间变化，自动计算天数和总价
watch([() => bookingForm.value.startTime, () => bookingForm.value.endTime], () => {
  if (bookingForm.value.startTime && bookingForm.value.endTime) {
    const start = new Date(bookingForm.value.startTime);
    const end = new Date(bookingForm.value.endTime);

    // 计算天数（包括起始和结束日期）
    const timeDiff = end.getTime() - start.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
    bookingForm.value.days = daysDiff > 0 ? daysDiff : 1; // 至少为1天

    // 计算总价
    bookingForm.value.visitorPayment = bookingForm.value.days * (selectedGuide.value.price || 0);
  } else {
    bookingForm.value.days = 0;
    bookingForm.value.visitorPayment = 0;
  }
})

// 提交预约
const submitBooking = async () => {
  if (!bookingForm.value.startTime || !bookingForm.value.endTime) {
    ElMessage.warning('请选择预约开始时间和结束时间');
    return;
  }

  if (bookingForm.value.days <= 0) {
    ElMessage.warning('预约天数必须大于0');
    return;
  }

  if (!currentVisitorId.value) {
    ElMessage.warning('未获取到用户信息');
    return;
  }

  // 检查开始时间不能晚于结束时间
  if (new Date(bookingForm.value.startTime) > new Date(bookingForm.value.endTime)) {
    ElMessage.warning('开始时间不能晚于结束时间');
    return;
  }

  ElMessageBox.confirm(
      `确认预约地陪 ${selectedGuide.value.username} 吗？`,
      '确认预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const bookingData = {
        visitorId: currentVisitorId.value,
        guideId: selectedGuide.value.id,
        guideName: selectedGuide.value.username,
        startTime: bookingForm.value.startTime,
        endTime: bookingForm.value.endTime,
        days: bookingForm.value.days,
        visitorPayment: bookingForm.value.visitorPayment,
        isDeleted: 0
      };

      // 调用预约API
      const response = await booking_api.add(bookingData);

      bookingDialogVisible.value = false;

      // 重新加载预约记录（回到第一页）
      bookingPage.value.currentPage = 1;
      await loadBookings();
    } catch (error) {
      console.error('预约失败:', error);
      // 检查是否是时间冲突错误
      if (error.message && (error.message.includes('已被预约') || error.message.includes('冲突'))) {
        ElMessage.error('预约失败：该导游在所选时间段内已被预约，请选择其他时间');
      } else {
        ElMessage.error('预约失败: ' + (error.message || '未知错误'));
      }
    }
  }).catch(() => {
    ElMessage.info('已取消预约');
  });
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.getFullYear() + '-' +
      String(date.getMonth() + 1).padStart(2, '0') + '-' +
      String(date.getDate()).padStart(2, '0');
}

// 取消预约记录
const cancelBookingRecord = (row) => {
  // 检查预约是否已经取消
  if (row.isDeleted === 1 || row.status === '已取消') {
    ElMessage.warning('该预约已取消，无需重复操作');
    return;
  }

  ElMessageBox.confirm(
      `确定要取消预约"${row.guideName}"的服务吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      // 调用API删除数据
      await booking_api
          .delete(row.id);
      ElMessage.success('预约已取消');
      // 重新加载预约记录
      await loadBookings();
    } catch (error) {
      ElMessage.error('取消预约失败: ' + error.message);
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

// 判断预约是否已失效（到了开始时间但未支付）
const isBookingInvalid = (row) => {
  if (!row.startDate || row.isPaid || row.isDeleted === 1 || row.status === '已取消') {
    return false;
  }

  const startDate = new Date(row.startDate);
  const today = new Date();
  startDate.setHours(0, 0, 0, 0)
  today.setHours(0, 0, 0, 0); // 将时间设置为当天凌晨，只比较日期

  return startDate <= today;
}

// 添加处理支付的函数
const handlePayment = async (row) => {
  // 检查预约是否已经支付或取消
  if (row.isDeleted === 1 || row.status === '已取消') {
    ElMessage.warning('该预约已取消，无法支付');
    return;
  }

  // 检查是否已经支付
  if (row.isPaid) {
    ElMessage.warning('该预约已经支付');
    return;
  }

  ElMessageBox.confirm(
      `确定要支付预约"${row.guideName}"的服务费用吗？费用：${row.amount}`,
      '确认支付',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      // 构造交易记录数据
      const transactionData = {
        bookingId: row.id,
        visitorId: currentVisitorId.value,
        visitorName: visitorInfo.value?.username || '',
        guideId: row.guideId,
        guideName: row.guideName,
        visitorPayment: row.rawData.visitorPayment,
        guideSalary: row.rawData.visitorPayment,
        date: new Date(),
        isDeleted: 0
      };

      // 调用API创建交易记录
      const response = await transaction_api.create(transactionData);
      console.log(response)

      if (response && (typeof response === 'string' || response.code === 200)) {
        ElMessage.success('支付成功');

        // 更新本地数据状态，标记为已支付
        const bookingIndex = bookings.value.findIndex(item => item.id === row.id);
        if (bookingIndex !== -1) {
          bookings.value[bookingIndex].isPaid = 1;// 已支付
        }
      } else {
        throw new Error(response?.msg || '支付失败');
      }
    } catch (error) {
      console.error('支付失败:', error);
      ElMessage.error('支付失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消支付');
  });
}

// 打开评分对话框
const openRatingDialog = (row) => {
  // 检查是否已经评分
  if (row.isRated) {
    ElMessage.warning('您已经对该地陪进行过评分');
    return;
  }

  currentBooking.value = row;
  ratingForm.value = {
    guideId: row.guideId,
    rates: 5
  };
  ratingDialogVisible.value = true;
}

// 提交评分
const submitRating = async () => {
  if (!currentVisitorId.value) {
    ElMessage.warning('未获取到用户信息');
    return;
  }

  if (!ratingForm.value.guideId) {
    ElMessage.warning('缺少地陪信息');
    return;
  }

  if (ratingForm.value.rates < 1 || ratingForm.value.rates > 5) {
    ElMessage.warning('评分必须在1-5之间');
    return;
  }

  ElMessageBox.confirm(
      `确定要为地陪"${currentBooking.value.guideName}"打${ratingForm.value.rates}分吗？`,
      '确认评分',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const ratingData = {
        visitorId: currentVisitorId.value,
        guideId: ratingForm.value.guideId,
        rates: ratingForm.value.rates
      };

      // 调用评分API
      const response = await vRateApi.add(ratingData);

      if (response) {
        ElMessage.success('评分成功');
        ratingDialogVisible.value = false;

        // 更新本地数据状态，标记为已评分
        const bookingIndex = bookings.value.findIndex(item => item.id === currentBooking.value.id);
        if (bookingIndex !== -1) {
          bookings.value[bookingIndex].isRated = 1;
        }

        // 同时更新地陪列表中的评分
        const guideIndex = guides.value.data.findIndex(guide => guide.id === ratingForm.value.guideId);
        if (guideIndex !== -1) {
          // 重新获取该地陪的评分
          try {
            const res = await vRateApi.getRate({ guideId: ratingForm.value.guideId });
            guides.value.data[guideIndex].rate = res ? parseFloat(res.toFixed(1)) : 0;
          } catch (error) {
            console.error('更新地陪评分失败:', error);
          }
        }
      } else {
        throw new Error('评分失败');
      }
    } catch (error) {
      console.error('评分失败:', error);
      ElMessage.error('评分失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消评分');
  });
}


// 添加获取游客信息的函数
const visitorInfo = ref(null);

const loadVisitorProfile = async () => {
  try {
    const payload = getJwtPayload();
    if (!payload || (payload.ID == null && payload.id == null)) {
      throw new Error('未从 token 中读取到用户 ID');
    }
    const currentVisitorId = Number(payload.ID ?? payload.id);

    const result = await visitor_api.find(currentVisitorId);
    visitorInfo.value = result;
  } catch (error) {
    console.error('获取游客信息失败:', error);
    ElMessage.error('获取个人信息失败: ' + error.message);
  }
};

</script>

<template>
  <div class="booking-container">
    <!-- 地陪列表卡片 -->
    <el-card class="guide-list-card">
      <template #header>
        <div class="card-header">
          <span>地陪列表</span>
          <div class="search-box">
            <el-input v-model="searchObj.username" placeholder="姓名" class="search-input"/>
            <el-select v-model="searchObj.gender" placeholder="性别" class="search-select">
              <el-option label="全部" value=""/>
              <el-option label="男" value="1"/>
              <el-option label="女" value="0"/>
            </el-select>
            <el-input v-model="searchObj.position" placeholder="位置" class="search-input"/>
            <el-button type="primary" @click="handleSearch" class="search-button">查询</el-button>
            <el-button @click="handleReset" class="reset-button">重置</el-button>
          </div>
        </div>
      </template>

      <div class="guide-list">
        <div v-for="guide in availableGuides" :key="guide.id" class="guide-item">
          <el-avatar :size="50" :src="getOssImageUrl(guide.image)" :icon="Picture" class="guide-avatar"/>
          <div class="guide-info">
            <div class="guide-name">{{ guide.username }}</div>
            <div class="guide-details">
              <span class="detail-item">性别: {{ guide.gender === 1 ? '男' : '女' }}</span>
              <span class="detail-item">位置: {{ guide.position }}</span>
              <span class="detail-item">价格: {{ guide.price }}元/天</span>
              <span v-if="guide.age" class="detail-item">年龄: {{ guide.age }}岁</span>
              <span v-if="guide.height" class="detail-item">身高: {{ guide.height }}cm</span>
              <span v-if="guide.weight" class="detail-item">体重: {{ guide.weight }}g</span>
              <span class="detail-item">
                评分:
                <el-rate
                    v-model="guide.rate"
                    disabled
                    show-score
                    score-template="{value}分"
                    :max="5"
                    size="small"
                />
              </span>
            </div>
          </div>
          <div class="guide-actions">
            <el-button type="primary" @click="openBookingDialog(guide)" class="book-button">预约</el-button>
          </div>
        </div>

        <div v-if="availableGuides.length === 0" class="empty-tip">
          暂无可用地陪
        </div>
      </div>

      <div class="pagination">
        <el-pagination
            v-model:current-page="searchObj.currentPage"
            v-model:page-size="searchObj.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :total="guides.totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预约对话框 -->
    <el-dialog v-model="bookingDialogVisible" title="预约地陪" width="500px" class="booking-dialog">
      <el-form :model="bookingForm" label-width="100px" class="booking-form">
        <el-form-item label="地陪姓名">
          <el-input v-model="selectedGuide.username" disabled/>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="bookingForm.startTime"
              type="date"
              placeholder="选择开始日期"
              :disabled-date="disabledStartDate"
              value-format="YYYY-MM-DD"
              class="date-picker"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="bookingForm.endTime"
              type="date"
              placeholder="选择结束日期"
              :disabled-date="disabledEndDate"
              value-format="YYYY-MM-DD"
              class="date-picker"
          />
        </el-form-item>
        <el-form-item label="天数">
          <el-input-number v-model="bookingForm.days" :min="1" disabled class="days-input"/>
        </el-form-item>
        <el-form-item label="总费用">
          <el-input v-model="bookingForm.visitorPayment" disabled class="total-fee-input">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bookingDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitBooking" class="confirm-button">确认预约</el-button>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog v-model="ratingDialogVisible" title="地陪评分" width="500px" class="rating-dialog">
      <el-form label-width="100px" class="rating-form">
        <el-form-item label="地陪姓名">
          <el-input v-model="currentBooking.guideName" disabled/>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate
              v-model="ratingForm.rates"
              :max="5"
              show-score
              score-template="{value}分"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="ratingDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitRating" class="confirm-button">提交评分</el-button>
      </template>
    </el-dialog>

    <!-- 我的预约卡片 -->
    <el-card class="booking-list-card">
      <template #header>
        <div class="card-header">
          <span>我的预约</span>
        </div>
      </template>

      <el-table :data="bookings"
                :row-class-name="(row) => isBookingInvalid(row.row) ? 'invalid-row' : ''"
                style="width: 100%"
                class="booking-table">
        <el-table-column prop="guideName" label="地陪姓名" width="120"/>
        <el-table-column prop="startDate" label="开始日期" width="120"/>
        <el-table-column prop="endDate" label="结束日期" width="120"/>
        <el-table-column prop="days" label="天数" width="80"/>
        <el-table-column prop="amount" label="费用" width="100"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已预约' && !isBookingInvalid(scope.row) ? 'success' : 'info'"
                    class="status-tag">
              {{ isBookingInvalid(scope.row) ? '已失效' : scope.row.status }}
            </el-tag>
            <el-tag :type="scope.row.isPaid ? 'success' : 'warning'"
                    size="small" class="payment-tag">
              {{ scope.row.isPaid ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="booking-actions">
              <el-button
                  v-if="scope.row.isDeleted !== 1 && scope.row.status !== '已取消' && !scope.row.isPaid && !isBookingInvalid(scope.row)"
                  type="primary"
                  size="small"
                  @click="handlePayment(scope.row)"
                  class="pay-button"
              >
                支付
              </el-button>
              <el-tag
                  v-else-if="scope.row.isPaid"
                  type="success"
                  size="small"
                  class="paid-tag"
              >
                已支付
              </el-tag>
              <el-button
                  v-if="scope.row.isPaid && !scope.row.isRated"
                  type="warning"
                  size="small"
                  @click="openRatingDialog(scope.row)"
                  class="rate-button"
              >
                评分
              </el-button>
              <el-tag
                  v-else-if="scope.row.isRated"
                  type="warning"
                  size="small"
                  class="rated-tag"
              >
                已评分
              </el-tag>
              <el-button
                  v-if="scope.row.isDeleted !== 1 && scope.row.status !== '已取消' && !scope.row.isPaid && !isBookingInvalid(scope.row)"
                  type="danger"
                  size="small"
                  @click="cancelBookingRecord(scope.row)"
                  class="cancel-button"
              >
                取消预约
              </el-button>
              <span v-if="scope.row.isDeleted === 1 || scope.row.status === '已取消'"
                    class="cancelled-text">已取消</span>
              <span v-if="isBookingInvalid(scope.row)"
                    class="invalid-text">已失效</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加预约记录分页 -->
      <div class="booking-pagination">
        <el-pagination
            v-model:current-page="bookingPage.currentPage"
            v-model:page-size="bookingPage.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="bookingPage.totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleBookingSizeChange"
            @current-change="handleBookingCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.booking-container {
  padding: 20px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  min-height: 100%;
}

.guide-list-card,
.booking-list-card {
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
  border: none;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
}

:deep(.guide-list-card .el-card__header),
:deep(.booking-list-card .el-card__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  border-radius: 15px 15px 0 0 !important;
  padding: 20px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input,
.search-select {
  border: 1px solid #d1e1ff;
  border-radius: 8px;
}

.search-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  color: white;
  font-weight: 500;
}

.reset-button {
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  border: 1px solid #409eff;
  color: #409eff;
  font-weight: 500;
}

.guide-list {
  padding: 15px;
}

.guide-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e6f7ff;
  border-radius: 10px;
  margin-bottom: 10px;
  background: #f8fbff;
  transition: all 0.3s ease;
}

.guide-item:hover {
  background: #e6f7ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.guide-avatar {
  border: 2px solid #409eff;
  border-radius: 50%;
}

.guide-info {
  flex: 1;
  margin-left: 15px;
}

.guide-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #409eff;
  font-size: 16px;
}

.guide-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.detail-item {
  padding: 2px 8px;
  background: #e6f7ff;
  border-radius: 12px;
  font-size: 12px;
}

.guide-actions {
  margin-left: 15px;
}

.book-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  color: white;
  font-weight: 500;
  border-radius: 20px;
}

.empty-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
}

.pagination,
.booking-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #409eff;
}

.booking-dialog,
.rating-dialog {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.booking-dialog .el-dialog__header),
:deep(.rating-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  padding: 20px;
  border-radius: 15px 15px 0 0 !important;
}

:deep(.booking-dialog .el-dialog__title),
:deep(.rating-dialog .el-dialog__title) {
  color: #409eff;
  font-weight: 600;
}

.booking-form,
.rating-form {
  padding: 20px;
}

.date-picker,
.days-input,
.total-fee-input {
  width: 100%;
}

.cancel-button {
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  border: 1px solid #409eff;
  color: #409eff;
  font-weight: 500;
}

.confirm-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  color: white;
  font-weight: 600;
}

.booking-table {
  border-radius: 10px;
  overflow: hidden;
}

:deep(.booking-table th) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
}

.status-tag,
.payment-tag {
  margin-bottom: 3px;
}

.booking-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: center;
}

.pay-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  color: white;
  font-weight: 500;
  border-radius: 15px;
  padding: 6px 12px;
}

.rate-button {
  background: linear-gradient(135deg, #e6a23c, #f2c16d);
  border: none;
  color: white;
  font-weight: 500;
  border-radius: 15px;
  padding: 6px 12px;
}

.paid-tag,
.rated-tag {
  margin-bottom: 5px;
}

.cancel-button {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
  color: white;
  font-weight: 500;
  border-radius: 15px;
  padding: 6px 12px;
}

.cancelled-text {
  color: #909399;
  font-size: 12px;
}

@media (max-width: 768px) {
  .booking-container {
    padding: 15px;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .search-box {
    flex-wrap: wrap;
    width: 100%;
  }

  .search-input,
  .search-select {
    flex: 1;
    min-width: 45%;
  }

  .guide-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .guide-info {
    margin-left: 0;
    width: 100%;
  }

  .guide-details {
    flex-direction: column;
    gap: 5px;
  }

  .guide-actions {
    margin-left: 0;
    align-self: flex-end;
  }
}
</style>
